/* example get_node_info.c */
/* compile with: gcc -g -Wall get_node_info.c -o get_node_info -lvirt */
#include <stdio.h>
#include <stdlib.h>
#include <libvirt/libvirt.h>

int main(int argc, char *argv[])
{
    virConnectPtr conn;
    virNodeInfo nodeinfo;
    char *host;
    int vcpus;
    unsigned long long node_free_mem;
    unsigned long hyper_ver;
    unsigned long libvirt_ver;

    conn = virConnectOpen("qemu:///system");
    if (conn == NULL)
    {
        fprintf(stderr, "Failed to open connection to qemu:///system\n");
        return 1;
    }

    vcpus = virConnectGetMaxVcpus(conn, NULL);
    node_free_mem = virNodeGetFreeMemory(conn);
    hyper_ver = virConnectGetVersion(conn, &hyper_ver);
    libvirt_ver = virConnectGetLibVersion(conn, &libvirt_ver);

    host = virConnectGetHostname(conn);
    fprintf(stdout, "Hostname: \033[41;37m%s\033[0m\n\n", host);
    free(host);
    fprintf(stdout, "Virtualization type: \033[41;37m%s\033[0m\n\n", virConnectGetType(conn));

    fprintf(stdout, "Version: %lu\n", hyper_ver);
    fprintf(stdout, "Libvirt Version: %lu\n\n", libvirt_ver);

    fprintf(stdout, "Maximum support virtual CPUs: \033[41;37m%d\033[0m\n\n", vcpus);
    if (node_free_mem > 1024)
    {
        fprintf(stdout, "Node free memory: \033[41;37m%llu MB\033[0m\n\n", node_free_mem / 1024);
    }
    else
    {
        fprintf(stdout, "Node free memory: \033[41;37m%llu KB\033[0m\n\n", node_free_mem);
    }

    virNodeGetInfo(conn, &nodeinfo);

    fprintf(stdout, "CPU Model:                      %s\n", nodeinfo.model);
    if (nodeinfo.memory < 1024)
    {
        fprintf(stdout, "Memory size:                  %lu KB\n", nodeinfo.memory);
    }
    else
    {
        fprintf(stdout, "Memory size:                  %lu MB\n", nodeinfo.memory / 1024);
    }

    fprintf(stdout, "Number of CPUs:                 %u\n", nodeinfo.cpus);
    fprintf(stdout, "MHz of CPUs:                    %u\n", nodeinfo.mhz);
    fprintf(stdout, "Number of NUMA nodes:           %u\n", nodeinfo.nodes);
    fprintf(stdout, "Number of CPU sockets:          %u\n", nodeinfo.sockets);
    fprintf(stdout, "Number of CPU cores per socket: %u\n", nodeinfo.cores);
    fprintf(stdout, "Number of CPU threads per core: %u\n", nodeinfo.threads);

    virConnectClose(conn);
    return 0;
}
